﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using BusinessEntity;
using BusinessLogic;
using Centaline.Common;
using CentalineWeb.Common;
using Newtonsoft.Json;

namespace CentalineWeb.server
{
    public partial class Login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            var action = Request.QueryString["Action"];
            switch (action)
            {
                case "CheckLogin":
                    CheckLogin();
                    break;
                case "logout":
                    Logout();
                    break;
            }

        }

        private void Logout()
        {
            HttpContext.Current.Session["user"] = null;
            Response.Redirect("~/Login.aspx");
        }

        private void CheckLogin()
        {
            ResultModel result = null;

            var user = ADLogin.GetSearchResult(ConfigurationManager.AppSettings["domainname"],
                Request["txtUserAccount"].Decode(), Request["txtUserPassword"].Decode());
            if (user != null)
            {
                var loginUser= new User()
                {
                    UserId = Request["txtUserAccount"].Decode(),
                    FullName = user.Properties["name"][0].ToString()
                };
                result = ResultModel.ReturnSuccess("登录成功！");
                CheckAndAddNewUser(Request["txtUserAccount"].Decode(),user.Properties["name"][0].ToString());

                var newuser = new UserManager().GetUserByUserId(loginUser.UserId);
                var isAdmin = string.IsNullOrEmpty(Request.QueryString["isAdmin"]);
                if (newuser.RoleId == 1) //是管理员，但是没有勾选以管理员登录,则以报修人员角色登录
                {
                    if (isAdmin)
                    {
                        newuser.RoleId = 3;

                    }
                    else
                    {
                        newuser.RoleId = 1;
                        
                    }
                }
                Session["user"] = newuser;
            }
            else
            {
                Session["user"] = null;
                result = ResultModel.ReturnFail("用户名或密码输入错误!");
            }
            Response.Write(JsonConvert.SerializeObject(result));
        }

        private void CheckAndAddNewUser(string userId,string userName)
        {
            var us = new UserManager();
            if (!us.IsExitByUserId(userId))
            {
                us.AddOneByUserId(userId, userName);
            }
        }
    }
}